package vip.xiaonuo.modular.encryptAndDecrypt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import vip.xiaonuo.core.annotion.Decrypt;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.util.RsaUtil;

import java.lang.reflect.Type;

/**
 * 接收解密DecryptRequstBodyAdvice
 *
 * @author zhangbixi
 * @date 2021/08/05
 */
@RestControllerAdvice
public class DecryptRequstBodyAdvice implements RequestBodyAdvice {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private boolean decrypt;
    public DecryptRequstBodyAdvice() {
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (methodParameter.getMethod().isAnnotationPresent(Decrypt.class) && ConstantContextHolder.getRSAFlag()) {
            this.decrypt = true;
        }

        return this.decrypt;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (this.decrypt) {
            try {
                return new DecryptHttpInputMessage(inputMessage, RsaUtil.getPrivateKey(), false);
            } catch (Exception var6) {
                this.log.error("Decryption failed", var6);
            }
        }
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
